<template>
    <div class="box">
        <div class="header">
        <van-nav-bar
            title="地址列表"
            left-arrow
            @click-left="onClickLeft" />
        </div>
        <div class="content">
            <van-address-list
              v-model="chosenAddressId"
              :list="list"
              :disabled-list="disabledList"
              disabled-text="以下地址超出配送范围"
              default-tag-text="默认"
              @add="goAdd"
              @edit="goEdit"
              @click-item="select"
              />
        </div>
    </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, AddressList } from 'vant'
import { getList, updateOrderAddress } from '@/api/order'
import { areaList } from '@vant/area-data'

Vue.use(NavBar)
Vue.use(AddressList)
export default {
  data () {
    return {
      areaList,
      paramsList: [],
      chosenAddressId: '1',
      list: [],
      disabledList: [],
      userid: localStorage.getItem('userid')
    }
  },
  computed: {
    time () {
      return location.href.split('addresslist/')[1]
    }
  },
  async mounted () {
    // 获取处理list数据
    var res = await getList({ userid: this.userid })
    this.paramsList = res
    res.forEach((item, index) => {
      this.list.push({})
      this.list[index].id = index
      this.list[index].name = item.name
      this.list[index].tel = item.tel
      this.list[index].isDefault = item.isDefault
      // this.list[index].province = item.province
      // this.list[index].city = item.city
      this.list[index].county = item.county
      this.list[index].address = item.province + item.city + item.county + item.addressDetail
      this.list[index].addressDetail = item.addressDetail
      this.list[index].addressid = item.addressid
    })
  },
  methods: {
    onClickLeft () {
      this.$router.back()
    },
    goAdd () {
      this.$router.push({ name: 'addaddress', params: { time: this.time } })
    },
    goEdit (item) {
      console.log(areaList)
      var code = this.findKey(areaList.county_list, item.county)
      item.areaCode = code
      this.$router.push({ name: 'editaddress', params: item })
    },
    select (item, index) {
      var params = {
        userid: this.userid,
        name: item.name,
        tel: item.tel,
        province: this.paramsList[index].province,
        city: this.paramsList[index].city,
        county: this.paramsList[index].county,
        addressDetail: this.paramsList[index].addressDetail,
        time: this.time
      }
      updateOrderAddress(params)
    },
    findKey (data, value, compare = (a, b) => a === b) {
      return Object.keys(data).find(k => compare(data[k], value))
    }
  }
}
</script>

<style>

</style>
